package com.zhiche.lisa.oms.service.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.oms.dao.model.bo.GenerateShipOrderBO;
import com.zhiche.lisa.oms.vo.ShipOrderVo;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class TmsUtil {

    @Value("${lisa.tms.generateShipOrderURL}")
    private String generateShipOrder;

    @Value("${lisa.tms.getShipOrderByItemIdURL}")
    private String getShipOrderByItemIdURL;

    //连接超时时间
    @Value("${lisa.socketTimeout}")
    private int socketTimeout;

    public ShipOrderVo getShipOrderInfo(String authorization, Long itemId) {
        ShipOrderVo shipOrder = null;
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization",authorization));
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("itemId", String.valueOf(itemId)));
        String strReturn = HttpClientUtil.get(getShipOrderByItemIdURL,headNamePairs,params,socketTimeout);
        if(!StringUtils.isEmpty(strReturn)){
            RestfulResponse<ShipOrderVo> restVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<ShipOrderVo>>(){});
            shipOrder = restVO.getData();
        }
        return shipOrder;
    }

    public void generateShipOrder(String authorization,GenerateShipOrderBO generateShipOrderBO) {
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization",authorization));
        String strReturn = HttpClientUtil.postJson(generateShipOrder, headNamePairs, JSON.toJSONString(generateShipOrderBO), socketTimeout);
        Integer code = null;
        String message = null;
        if(!StringUtils.isEmpty(strReturn)){
            RestfulResponse<ShipOrderVo> restVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<ShipOrderVo>>(){});
            code = restVO.getCode();
            message = restVO.getMessage();
        }

        if (StringUtils.isEmpty(strReturn) ||
                code!=0) {
            throw new BaseException("生成运单异常：" + message);
        }
    }

}
